import { useEffect, useRef, useState } from "react";
import { clearTimeout, setTimeout } from "timers";

export const isFalsy = (value: unknown) => value === 0 ? false : !value;

export const isVoid = (value: unknown) => value === undefined || value === null || value === '';

//在一个函数，改变传入的对象不好
export const cleanObject = (object: {[key: string ]: unknown}) => {
  const result = {...object};
  Object.keys(result).forEach(key => {
    //@ts-ignore
    const value = result[key];
    let isvoid = isVoid(value)
    console.log('is void: ', isvoid)
    if (isvoid) {
      //@ts-ignore
      console.log('exec delete')
      delete result[key];
    }
  })
  console.log('clean object result: ', result)
  return result;
}

export const useMount = (callback: () => void) => {
  useEffect(() => {
    callback()
    // TODO 依赖项里加上callback，会造成无限循环，和useCallback useMemo有关系
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])
}

export const useDebounce = <V>(value: V, delay?: number) => {
  //内部变量 debouncedValue
  const [debouncedValue, setDebouncedValue] = useState(value);
  useEffect(() => {
    //每次在value变化以后 设置一个定时器
    const timeout = setTimeout(() => {
      setDebouncedValue(value);
      //第二个清理第一个
      return () => clearTimeout(timeout);
    }, delay || 500);
    
  }, [value, delay]);
  return debouncedValue;
}

export const resetRoute = () => {
  window.location.href = window.location.origin
}

/**
 * 返回组件的挂载状态， 如果还没挂载或者已经卸载，返回false
 */
export const useMountedRef = () => {
  const mountedRef = useRef(false)
  useEffect(() => {
    mountedRef.current = true
    return () => {
      mountedRef.current = false
    }
  })
  return mountedRef
}